const path = require('path');
var prod = process.env.NODE_ENV === 'production';
var project = process.env.project;
var type = process.env.miniprograme;
var fs = require('fs');
var copyFile = function (srcPath, tarPath, cb) {
  var rs = fs.createReadStream(srcPath)
  rs.on('error', function (err) {
    if (err) {
      console.log('read error', srcPath)
    }
    cb && cb(err)
  })

  var ws = fs.createWriteStream(tarPath)
  ws.on('error', function (err) {
    if (err) {
      console.log('write error', tarPath)
    }
    cb && cb(err)
  })
  ws.on('close', function (ex) {
    cb && cb(ex)
  })

  rs.pipe(ws)
}
var copyFolder = function (srcDir, tarDir, cb) {
  fs.readdir(srcDir, function (err, files) {
    var count = 0
    var checkEnd = function () {
      ++count == files.length && cb && cb()
    }

    if (err) {
      checkEnd()
      return
    }

    files.forEach(function (file) {
      var srcPath = path.join(srcDir, file)
      var tarPath = path.join(tarDir, file)

      fs.stat(srcPath, function (err, stats) {
        if (stats.isDirectory()) {
          console.log('mkdir', tarPath)
          fs.mkdir(tarPath, function (err) {
            if (err) {
              console.log(err)
              return
            }

            copyFolder(srcPath, tarPath, checkEnd)
          })
        } else {
          copyFile(srcPath, tarPath, checkEnd)
        }
      })
    })

    //为空时直接回调
    files.length === 0 && cb && cb()
  })
}
function delDir(p) {
  // 读取文件夹中所有文件及文件夹
  try {
    var list = fs.readdirSync(p)
    list.forEach((v, i) => {
      // 拼接路径
      var url = p + '/' + v
      // 读取文件信息
      var stats = fs.statSync(url)
      // 判断是文件还是文件夹
      if (stats.isFile()) {
        // 当前为文件，则删除文件
        fs.unlinkSync(url)
      } else {
        // 当前为文件夹，则递归调用自身
        arguments.callee(url)
      }
    })
    // 删除空文件夹
    fs.rmdirSync(p)
  } catch (error) {

  }


}
function newPackageA() {
  fs.mkdir("./commondist/packageA/home", function (err) {
    if (err) {
      return console.error(err);
    }
    fs.writeFileSync("./commondist/packageA/home/home.wpy", fs.readFileSync("./src/packageA/pages/home/home.wpy"));
  });
}
function adapterAppJSON() {
  fs.readFile("./commondist/app.json", (err, data) => {
    let info = JSON.parse(data.toString());
    info.miniprogramename = { cd: "成都", tm: "特卖" }[type];
    if (type == 'cd') info.navigateToMiniProgramAppIdList = info.navigateToMiniProgramAppIdListcd;
    if (type == 'tm') info.navigateToMiniProgramAppIdList = info.navigateToMiniProgramAppIdListtm;

    fs.writeFile("./commondist/app.json", JSON.stringify(info), function (error) {
      if (error) {
        console.log('写入失败')
      } else {
        console.log('写入成功了')
      }
    })
  })
}

prod && type && adapterAppJSON();
prod && delDir('./commondist');
newPackageA();
copyFolder("./src/vant", "./commondist/vant");

// fs.writeFileSync("./commondist/vant", fs.readFileSync("./src/vant"));
const companyDict = {
  dist: "gb",
  mc: "mc",
  lc: "lc",
  gb: "gb",
  kc: "kc",
  sport: "sport",
  "2c": "2c",
  nike: "nike",
  adidasjm: "adidasjm",
  adidas: "adidas",
  charle: "charle",
  ua: "ua",
  dist: "cd",
  gbstation: "gbstation"
}
module.exports = {
  target: project || 'newcloudmall',
  wpyExt: '.wpy',
  eslint: false,
  cliLogs: !prod,
  build: {
    web: {
      htmlTemplate: path.join('src', 'index.template.html'),
      htmlOutput: path.join('web', 'index.html'),
      jsOutput: path.join('web', 'index.js')
    }
  },
  resolve: {
    alias: {
      counter: path.join(__dirname, 'src/components/counter'),
      '@': path.join(__dirname, 'src')
    },
    aliasFields: ['wepy', 'weapp'],
    modules: ['node_modules']
  },
  compilers: {
    less: {
      compress: prod
    },
    /*sass: {
      outputStyle: 'compressed'
    },*/
    babel: {
      sourceMap: true,
      presets: [
        'env'
      ],
      plugins: [
        'transform-class-properties',
        'transform-decorators-legacy',
        'transform-object-rest-spread',
        'transform-export-extensions',
      ]
    }
  },
  plugins: {
  },
  appConfig: {
    isMc: project == "mc",
    shopId: project == "mc" ? "864" : "",
    noPromiseAPI: ['createSelectorQuery'],
    company: companyDict[project]
  }
}

if (prod) {


  // 压缩sass
  //  module.exports.compilers['sass'] = {outputStyle: 'compressed'}

  // 压缩js
  module.exports.plugins = {
    uglifyjs: {
      filter: /\.js$/,
      config: {
      }
    },
    'filemin': {
      filter: /\.(json|wxml|xml)$/
    },

    imagemin: {
      filter: /\.(jpg|png|jpeg)$/,
      config: {
        jpg: {
          quality: 80
        },
        png: {
          quality: 80
        }
      }
    }
  }
}else{
  module.exports.plugins = {
    replace: {
      filter:/\.wxml|wpy$/,
      config: {
        find:/src=.+images/g,
        replace:'src="https://mamhao.gb246.com/images'
      }
    }}
}
 

